{% extends 'admin_dashboard.html' %}
{% block content %}
<div class="card">
  <h2>添加银行卡</h2>

  <form id="cardForm" method="POST">
    <div class="form-group">
      <label>所属客户编号</label>
        <select name="customerID" required>
        <option value="">请选择客户</option>
        {% for c in customers %}
        <option value="{{ c.customerID }}">{{ c.customerID }} - {{ c.customerName }}</option>
        {% endfor %}
        <!-- ✅ 新建客户选项，放在所有人名下面 -->
        <option value="__new__">➕ 新建客户</option>
      </select>
    </div>

    <div class="form-group">
      <label>卡号</label>
      <input type="text" name="cardID" required pattern="^10103576\d{8}$" title="卡号必须是16位数字，且以10103576开头">
    </div>

    <div class="form-group">
      <label>存款类型</label>
      <select name="savingID" required>
        <option value="">请选择</option>
        {% for d in deposit_types %}
          <option value="{{ d.savingID }}">{{ d.savingName }}</option>
        {% endfor %}
      </select>
    </div>

    <div class="form-group">
      <label>密码</label>
      <input type="text" name="pass" required>
    </div>

    <div class="form-group">
      <label>是否挂失</label>
      <input type="checkbox" name="IsReportLoss" style="margin-left:10px;">
    </div>

    <button type="submit" class="btn">提交</button>
    <a href="{{ url_for('cards') }}" class="btn">返回</a>
  </form>
</div>

<script>
document.querySelector('select[name="customerID"]').addEventListener('change', function() {
  if (this.value === '__new__') {
    const currentPath = window.location.pathname;
    window.location.href = "{{ url_for('add_customer') }}" + '?next=' + encodeURIComponent(currentPath) + '&from_card=1';
  }
});

document.getElementById('cardForm').addEventListener('submit', function (e) {
  e.preventDefault();

  const formData = new FormData(this);
  fetch('/cards/add', {
    method: 'POST',
    body: formData
  })
  .then(res => res.json())
  .then(data => {
    if (data.success) {
      alert('✅ 添加成功！');
      window.location.href = '/cards';
    } else {
      alert('❌ ' + data.message);
    }
  })
  .catch(err => {
    alert('⚠️ 请求失败，请稍后再试');
    console.error(err);
  });
});

// 页面加载时判断 URL，若带 ?from_card=1 参数，说明刚添加完客户，弹窗显示卡信息
window.addEventListener('load', () => {
  const urlParams = new URLSearchParams(window.location.search);
  if (urlParams.get('from_card') === '1') {
    // 弹窗内容固定写死，因为触发器银行卡默认规则固定
    alert(
      '✅ 客户添加成功！\n' +
      '🎉 已自动为其开通银行卡！\n\n' +
      '卡号：10103576XXXXXXXX\n' +
      '初始余额：1.00 元\n' +
      '密码：888888\n' +
      '存款类型：1（活期）'
    );
    // 清除参数避免重复弹窗
    history.replaceState(null, '', window.location.pathname);
  }
});
</script>

{% endblock %}
